﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using University.Workshop.Model;
using System.Globalization;
using System.Text.RegularExpressions;

namespace University.Workshop.Business
{
    public static class SearchAdvancedProduct
    {
        private static Collection<Product> _result = new Collection<Product>();
       
        public static Collection<Product> FilteringFields(String category, String price1, String price2, String priceCurrency, 
            String quantity1, String quantity2, String date1, String date2, String text)
        {
            FilteringByCategoryAndDate(category, date1, date2);
            //if (result == null || result.Count == 0)
            //{
            //    throw new BusinessException("No Products");
            //}
            FilteringByQuantity(quantity1, quantity2);
            FilteringByPrice(price1, price2, priceCurrency);
            SearchedProducts(text);
            return _result;
        }

        public static void FilteringByCategoryAndDate(String category, String date1, String date2)
        {
            if (category == "All Products")
            {
                if (date1 != DateTime.MinValue.ToString() && date2 != DateTime.MinValue.ToString())
                {
                    DateTime dateB = Convert.ToDateTime(date1, CultureInfo.CurrentCulture);
                    DateTime dateE = Convert.ToDateTime(date2, CultureInfo.CurrentCulture);
                    if (dateB < dateE)
                    {
                        _result = DataAccess.ProductDataAccess.GetProductsAuctionByDate(dateB, dateE);
                    }
                    else
                    {
                        throw new ValidationException("Invalids selected dates");
                    }
                }
                else
                {
                    if ((date1 != DateTime.MinValue.ToString() && date2 == DateTime.MinValue.ToString()) || (date1 == DateTime.MinValue.ToString() && date2 != DateTime.MinValue.ToString()))
                    {
                        throw new ValidationException("Must selected both dates");
                    }
                    else
                    {
                        _result = DataAccess.ProductDataAccess.Products();
                    }
                }
            }
            else
            {
                if (date1 != DateTime.MinValue.ToString() && date2 != DateTime.MinValue.ToString())
                {
                    DateTime dateB = Convert.ToDateTime(date1, CultureInfo.CurrentCulture);
                    DateTime dateE = Convert.ToDateTime(date2, CultureInfo.CurrentCulture);
                    if (dateB < dateE)
                    {
                        _result = DataAccess.ProductDataAccess.GetProductsAuctionByCategoryAndDate(category, dateB, dateE);
                    }
                    else
                    {
                        throw new ValidationException("Invalids selected dates");
                    }
                }
                else
                {
                    _result = DataAccess.ProductDataAccess.GetProductsAuctionByCategory(category);
                }
            }
        }

        public static void FilteringByQuantity(String quantity1, String quantity2)
        {
            Collection<Product> list = new Collection<Product>();
            if (!String.IsNullOrEmpty(quantity1) && !String.IsNullOrEmpty(quantity2))
            {
                
                    String numbers = @"^[0-9]+$";
                    if (!Regex.IsMatch(quantity1, numbers) || !Regex.IsMatch(quantity2, numbers))
                    {
                        throw new ValidationException("Invalid quantity");
                    }
                    else
                    {
                        if (Convert.ToInt32(quantity1, CultureInfo.CurrentCulture) <= Convert.ToInt32(quantity2, CultureInfo.CurrentCulture))
                        {
                            foreach (Product obj in _result)
                            {
                                if (obj.Quantity >= Convert.ToInt32(quantity1, CultureInfo.CurrentCulture) && obj.Quantity <= Convert.ToInt32(quantity2, CultureInfo.CurrentCulture))
                                {
                                    list.Add(obj);
                                }
                            }
                            _result = list;
                        }
                        else
                        {
                            throw new ValidationException("Invalid quantity range");
                        }
                    }
            }
            else
            {
                if (!String.IsNullOrEmpty(quantity1))
                {
                    throw new ValidationException("Invalid quantity range");
                }
                if (!String.IsNullOrEmpty(quantity2))
                {
                    throw new ValidationException("Invalid quantity range");
                }
            }
        }

        public static void FilteringByPrice(String price1, String price2, String currency)
        {
            if (!String.IsNullOrEmpty(price1) && !String.IsNullOrEmpty(price2) && !String.IsNullOrEmpty(currency))
            {
                
                    String numbers = @"^[0-9.,]+$";
                    float BolivianosPrice1 = 0, BolivianosPrice2 = 0, DollarsPrice1 = 0, DollarsPrice2 = 0;
                    if (!Regex.IsMatch(price1, numbers) || !Regex.IsMatch(price2, numbers))
                    {
                        throw new ValidationException("Invalid price");
                    }
                    else
                    {
                        if (float.Parse(price2, CultureInfo.CurrentCulture) >= float.Parse(price1, CultureInfo.CurrentCulture))
                        {
                            Collection<Product> list = new Collection<Product>();
                            if (currency == "Bolivianos")
                            {
                                BolivianosPrice1 = float.Parse(price1, CultureInfo.CurrentCulture);
                                BolivianosPrice2 = float.Parse(price2, CultureInfo.CurrentCulture);
                                DollarsPrice1 = CompareProductsManager.BSToDollars(BolivianosPrice1);
                                DollarsPrice2 = CompareProductsManager.BSToDollars(BolivianosPrice2);
                            }
                            else
                            {
                                DollarsPrice1 = float.Parse(price1, CultureInfo.CurrentCulture);
                                DollarsPrice2 = float.Parse(price2, CultureInfo.CurrentCulture);
                                BolivianosPrice1 = CompareProductsManager.DollarsToBS(DollarsPrice1);
                                BolivianosPrice2 = CompareProductsManager.DollarsToBS(DollarsPrice2);
                            }
                            foreach (Product obj in _result)
                            {
                                if(obj.Currency=="Dollars")
                                {
                                    if (obj.Price <= DollarsPrice2)
                                    {
                                        if (obj.Price >= DollarsPrice1)
                                            list.Add(obj);
                                    }
                                }

                                else
                                {
                                    if(obj.Currency=="Bolivianos")
                                    {
                                        if (obj.Price <= BolivianosPrice2  )
                                        {
                                            if (obj.Price >= BolivianosPrice1)
                                                list.Add(obj);
                                        }
                                    }
                                }
                            }
                            _result = list;
                        }
                        else
                        {
                            throw new ValidationException("Invalid range of prices");
                        }
                    }
            }
            else
            {
                if (String.IsNullOrEmpty(price1))
                {
                    if (String.IsNullOrEmpty(price2))
                    {
                        if (!String.IsNullOrEmpty(currency))
                        {
                            throw new ValidationException("Must specify both price range and currency");
                        }
                    }
                    else
                    {
                        throw new ValidationException("Must specify both price range and currency");
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(price2))
                    {
                        throw new ValidationException("Must specify both price range and currency");
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(currency))
                        {
                            throw new ValidationException("Must specify both price range and currency");
                        }
                    }
                }
                
            }
        }

        //public static void FilteringByBidPrice(String bidPrice1, String bidPrice2, String bidCurrency)
        //{
        //    if (String.IsNullOrEmpty(bidPrice1) || String.IsNullOrEmpty(bidPrice2) || String.IsNullOrEmpty(bidCurrency))
        //    {
        //        throw new BusinessException("Must specify both bid price range and currency");
        //    }
        //    else
        //    {
        //        String numbers = @"^[0-9.,]+$";
        //        if (!Regex.IsMatch(bidPrice1, numbers) || !Regex.IsMatch(bidPrice2, numbers))
        //        {
        //            throw new ValidationException("Invalid bid price");
        //        }
        //        else
        //        {
        //            Collection<ProductAuction> list = new Collection<ProductAuction>();
        //            foreach (ProductAuction obj in result)
        //            {
        //                if (obj.Product.Price >= (float)Convert.ToDouble(bidPrice1, CultureInfo.CurrentCulture) && obj.Product.Price <= (float)Convert.ToDouble(bidPrice2, CultureInfo.CurrentCulture) && obj.Product.Currency == bidCurrency)
        //                {
        //                    list.Add(obj);
        //                }
        //            }
        //            result = list;
        //        }
        //    }
        //}

        public static void SearchedProducts(String sentence)
        {
            String[] words = null;
            String format = @"^[a-zA-Z0-9 ]";
            if (!String.IsNullOrEmpty(sentence))
            {
                if (!Regex.IsMatch(sentence, format))
                {
                    throw new ValidationException("Incorrect format input text");
                }
                words = SeparateWords(sentence);
                if (words != null)
                {
                    GetSearchProducts(words);
                    DropRepeatedValues();
                }
            }                
        }

        public static String[] SeparateWords(String sentence)
        {
            String[] words = null;
            if (!String.IsNullOrEmpty(sentence))
            {
                words = sentence.Split(' ');
            }
            return words;
        }        


        public static void DropRepeatedValues()
        {
            Collection<Product> noRepeatedValues = new Collection<Product>();
            int j = 0, i;
            if (_result != null && _result.Count != 0)
            {
                foreach (Product prod1 in _result)
                {
                    i = 0;
                    if (j == 0)
                    {
                        noRepeatedValues.Add(prod1);
                    }
                    foreach (Product prod2 in noRepeatedValues)
                    {
                        if (prod1.ProductId != prod2.ProductId)
                        {
                            if (i == noRepeatedValues.Count - 1)
                            {
                                noRepeatedValues.Add(prod1);
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                        i++;
                    }
                    j++;
                }
                _result = noRepeatedValues;
            }
        }

        public static void GetSearchProducts(String[] words)
        {
            Collection<Product> list = new Collection<Product>();
            if (words != null && words.Length != 0)
            {
                foreach (String word in words)
                {
                    foreach (Product prod in _result)
                    {
                        String name = prod.Name.ToLower(CultureInfo.CurrentCulture);
                        String description = prod.Description.ToLower(CultureInfo.CurrentCulture);
                        String lword = word.ToLower(CultureInfo.CurrentCulture);
                        if (!String.IsNullOrEmpty(word) && (name.Contains(lword) || description.Contains(lword)))
                        {
                            list.Add(prod);
                        }
                    }
                }
                _result = list;
            }
        }
    }
}
